package integrationTier.sql;

import core.MovieException;
import integrationTier.IDatabaseDAO;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;

/**
 * SQL DAO objekt k databazi
 * @author vojta
 */
public class DatabaseSQLDAO implements IDatabaseDAO{

    Statement stmt;

    public DatabaseSQLDAO(Connection cn) throws MovieException {
        try {
            stmt = cn.createStatement();
        } catch (SQLException ex) {
            throw new MovieException(ex);
        }
    }

    /**
     * Vytvori novou databazi
     * @throws MovieException
     */
    public void create() throws MovieException {
        try {
            String genres = "CREATE TABLE \"genres\"( \"id\" integer not null identity, \"genre\" VARCHAR(100))";
            String media = "CREATE TABLE \"media\" ( \"id\" INTEGER NOT NULL IDENTITY, \"medium\" VARCHAR(100))";
            String movies = "CREATE TABLE \"movies\" ( \"id\" INTEGER NOT NULL IDENTITY, \"name\" VARCHAR(100), \"year\" integer, \"director\" varchar(100), \"medium_id\" integer, \"genre_id\" integer)";
            stmt.executeUpdate(genres);
            stmt.executeUpdate(media);
            stmt.executeUpdate(movies);
        } catch (SQLException ex) {
            throw new MovieException(ex);
        }
    }

    /**
     * Ukonci pripojeni
     * @throws MovieException
     */
    public void close() throws MovieException {
        try {
            stmt.execute("SHUTDOWN");
            stmt.close();            
        } catch (SQLException ex) {
            throw new MovieException(ex);
        }
    }

}
